package com.example.springbootdemo.validate;

import com.example.springbootdemo.user.UserCmd;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.validation.*;
import java.util.Set;

public class ValidPhoneValidator implements ConstraintValidator<ValidPhone, Object> {

    private ApplicationContext applicationContext;

//    private Validator validator;
    @Override
    public void initialize(ValidPhone constraintAnnotation) {
//        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
//        validator = factory.getValidator();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        UserCmd userDTO = (UserCmd) value;
        if (StringUtils.equalsIgnoreCase(userDTO.getCountry(), "CN") && userDTO.getPhone() == null) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("国家为CN手机号不能为空").addConstraintViolation();
//            throw new IllegalArgumentException("国家为CN手机号不能为空");
            return false;
        }
        return true;

//         使用Validator来校验整个对象
//        Set<ConstraintViolation<UserCmd>> violations = validator.validate(userDTO);
//        return violations.isEmpty();

    }

//    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}